<template>
  <div>
    <!-- 容器 -->
    <div class="masonry-container" ref="containerRef">
      <div class="masonry-grid">
        <div v-for="(item, index) in dataSource" :key="item.id" class="masonry-item" ref="itemEls">
          <div class="responsive-image-frame">
            <template v-if="dataList[index].imageList[0]">
              <img :src="dataList[index].imageList[0].imgAbridgePath" :alt="dataList[index].text"
                class="responsive-image" loading="lazy" @load="imageLoad($event, index)"
                @click.stop="toDetail(dataList[index])" />
            </template>
            <div class=" icfont_box-wap" v-if="showIcon && getToken()">
              <div style="width: 35px ; height: 35px;">
                <div class="icon-real-wap" @click.stop="toggleIcon(dataList[index], '2')"
                  v-if="dataList[index].isLike === '1'">
                  <img src="../../assets/images/new_img/实心.png" alt="" class="img_png-wap" />
                </div>
                <div class="icon-empty-wap" @click.stop="toggleIcon(dataList[index], '1')" v-else>
                  <img src="../../assets/images/new_img/空心.png" alt="" class="img_png-wap" />
                </div>
              </div>
              <div style="width: 35px ; height: 35px;">
                <div class="icon-real-wap" @click.stop="toggleCollect(dataList[index], '2')"
                  v-if="dataList[index].isCollect === '1'">
                  <img src="../../assets/images/new_img/实心收藏.png" alt="" class="img_png-wap" />
                </div>
                <div class="icon-empty-wap" @click.stop="toggleCollect(dataList[index], '1')" v-else>
                  <img src="../../assets/images/new_img/空心收藏.png" alt="" class="img_png-wap" />
                </div>
              </div>
            </div>
            <div v-if="showPending">
              <div class="Pendingapproval" v-if="item.status == 1">
                待审核
              </div>
              <div class="Pendingapproval" v-if="item.status == 3">
                已驳回
              </div>
            </div>

            <div class="icon-edit" @click="toEdit(dataList[index], index)" v-if="isEdit">
              <FormOutlined />
            </div>
          </div>
          <div class="card-content-wap " @click="TOlistOfWorks(item)">
            <div class="text-wap">{{ dataList[index].picTitle }}</div>
            <div class="name-wap">
              <img :src="item.avatar" alt="" />
              <p>{{ dataList[index].realname }}</p>
            </div>
          </div>
        </div>

      </div>
    </div>

    <!-- 加载动画 -->
    <div v-if="loading" class="loading-container">
      <a-spin size="large" class="custom-spin" />
    </div>
    <!-- 触发懒加载的占位元素 -->
    <div v-else ref="myElement"></div>

    <div style="height: 50px"></div>

    <!-- 空数据提示 -->
    <div class="show-pc">
      <template v-if="(dataList.length === 0 && !loading) || !dataStatus">
        <a-empty description="我也是有底线的" style="color: var(--color-text);" />
      </template>
    </div>
    <div class="show-wap">
      <div style="padding-bottom: 100px;">
        <template v-if="(dataList.length === 0 && !loading) || !dataStatus">
          <a-empty description="我也是有底线的" style="color: var(--color-text);" />
        </template>
      </div>
    </div>

  </div>
</template>


<script setup>
import { ref, onMounted, onBeforeUnmount, watch, nextTick, defineExpose } from 'vue'
import { Spin as ASpin } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import { useHttp } from '~/api/http'
import { getToken } from '@/utils/token'
import { FormOutlined } from '@ant-design/icons-vue'
import { BASEURLTZ } from '@/utils/const'
import methods from '@/utils/methods'
import { useStore } from '@/store'
const { themeStore } = useStore()
const router = useRouter()
const emits = defineEmits(['toDetail', 'loadData', 'openEdit'])

const props = defineProps({
  col: { type: [String, Number], default: 6 },
  dataSource: { type: Array, default: [] },
  showIcon: { default: true, type: Boolean },
  loading: { default: false, type: Boolean },
  dataStatus: { default: true, type: Boolean },
  isEdit: { default: false, type: Boolean },
  showPending: { default: false, type: Boolean }
})

// refs
const containerRef = ref(null)
const itemEls = ref([])
const columnCount = ref(4)


const dataList = ref([])
dataList.value = methods.deepClone(props.dataSource)

watch(() => props.dataSource, (newVal, oldVal) => {
  dataList.value = methods.deepClone(newVal)
  setTimeout(() => {
    nextTick(layoutItems)
  }, 400)
  if (dataList.value.length === 0) {
    containerRef.value.style.height = `0px`
  }
  // setTimeout(() => {
  // 	window.scrollTo(0,1);
  // 	debouncedUpdate()
  // })
}, { deep: true })

// 监听窗口大小变化
let resizeTimer
const debouncedUpdate = () => {
  clearTimeout(resizeTimer)
  resizeTimer = setTimeout(() => {
    updateColumnCount()
    layoutItems()
  }, 100)
}

const updateColumnCount = () => {
  const width = window.innerWidth
  if (width <= 480) columnCount.value = 2
  else if (width <= 768) columnCount.value = 3
  else if (width <= 992) columnCount.value = 4
  else if (width <= 1200) columnCount.value = 5
  else columnCount.value = 6
}

// 初始化每个数据项的图标状态
const initIcons = () => {
  props.dataSource.forEach(item => {
    item.icons = {
      heart: { isSolid: false },
      star: { isSolid: false }
    };
    item.ok = false
  });
};

initIcons();

const imageLoad = (e, index) => {
  dataList.value[index].ok = true

  clearTimeout(resizeTimer)
  resizeTimer = setTimeout(() => {
    updateColumnCount()
    layoutItems()
  }, 100)
}

onBeforeUnmount(() => {
  window.removeEventListener('resize', debouncedUpdate)
  window.removeEventListener('scroll', handleScroll)
})

watch(() => props.dataStatus, value => {
  if (!value) {
    window.removeEventListener('scroll', handleScroll)
  } else {
    window.addEventListener('scroll', handleScroll)
  }
  // nextTick(() => {
  // 	window.scrollTo({
  // 		top: window.scrollY + 1, // 当前滚动位置向下100px
  // 		behavior: 'smooth' // 平滑滚动效果
  // 	});
  // })
})

onMounted(() => {
  window.addEventListener('scroll', handleScroll)
  window.addEventListener('resize', debouncedUpdate)
  updateColumnCount()
  layoutItems()
  setTimeout(() => {
    handleScroll()
  }, 1000)
})

onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll)
})
let maxHeight = 0
// Masonry 核心逻辑
const layoutItems = () => {
  const container = containerRef.value
  if (!container) return

  const items = itemEls.value


  if (!items.length) return

  // 清除之前的绝对定位
  items.forEach(el => {
    el.style.position = ''
    el.style.top = ''
    el.style.left = ''
  })

  const containerWidth = container.clientWidth
  const gap = 16
  const itemWidth = containerWidth / columnCount.value - gap * ((columnCount.value - 1) / columnCount.value)
  const columnsHeight = new Array(columnCount.value).fill(0)
 
  // if(itemWidth < 0) {
  // 	layoutItems()
  // 	return
  // }

  items.forEach((el, i) => {
    const columnIndex = getMinHeightIndex(columnsHeight)
    const left = (itemWidth + gap) * columnIndex
    const top = columnsHeight[columnIndex]

    el.style.position = 'absolute'
    el.style.left = `${left}px`
    el.style.top = `${top}px`

    columnsHeight[columnIndex] += el.offsetHeight + gap
  })

  // 设置容器高度为最大列高
  container.style.height = `${Math.max(...columnsHeight)}px`
  // maxHeight = Math.max(...columnsHeight) > maxHeight? Math.max(...columnsHeight): maxHeight
  // document.body.style.height = `${maxHeight}px`

  if(document.getElementsByClassName('masonry-grid').length > 0) {
    var height = document.getElementsByClassName('masonry-grid')[0].offsetHeight + 800
    document.body.style.height = `${height}px`
  }
  

}

function getMinHeightIndex(arr) {
  let minIndex = 0
  for (let i = 1; i < arr.length; i++) {
    if (arr[i] < arr[minIndex]) minIndex = i
  }
  return minIndex
}

// 路由跳转
const toDetail = (item) => {
  themeStore.searcShow.txet = '';
  themeStore.searcShow.visible = !themeStore.searcShow.visible
  themeStore.searcShow.inputValue = ''
  themeStore.activeKey = 0
  window.open(`${BASEURLTZ}/details/${item.id}`, "_blank ") 
}

// 点赞切换
const toggleIcon = (item, val) => {
  useHttp.get('/web/my/myLike', {
    picId: item.id,
  }).then((res) => {
    item.isLike = val
    getCount()
    message.success(res.message)
  })
}

// 收藏切换
const toggleCollect = async (item, val) => {

  useHttp.get('/web/my/myCollect', {
    picId: item.id,
  }).then((res) => {
    item.isCollect = val;
    getCount()
    message.success(res.message)
  })
}




// 点击编辑
const toEdit = (item, index) => {
  //   useHttp.get('/cms/pic/queryById?id=' + item.id).then(res => {
  //   })
  emits('openEdit', item.id, index)
}

// 获取数据
const changeData = (e) => {
  dataList.value[e.editIndex].picTitle = e.picTitle
  dataList.value[e.editIndex].imageList = e.imageList
}

// 获取数据
const delData = (e) => {
  dataList.value.splice(e.editIndex, 1)
}


// 滚动加载更多
const myElement = ref(null)

const checkIfElementInViewport = () => {
  if (myElement.value) {
    const rect = myElement.value.getBoundingClientRect()
    return (
      rect.top >= 0 &&
      rect.left >= 0 &&
      rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
      rect.right <= (window.innerWidth || document.documentElement.clientWidth)
    )
  }
  return false
}

const handleScroll = () => {
  if (checkIfElementInViewport()) {
    emits('loadData')
  }
}

defineExpose({
  changeData
})
// 用户主页
const TOlistOfWorks = (item) => {
  themeStore.searcShow.txet = '';
  themeStore.searcShow.visible = !themeStore.searcShow.visible
  themeStore.searcShow.inputValue = ''
  themeStore.activeKey = 0
  router.push({
    path: '/listOfWorks/' + item.createUserId,
  })

}

// 更新点赞数据
const heUserIdData = ref({
  heUserId: getUserId()
}); 
const getCount = () => {
  console.log( getUserId());
  
  useHttp.get('/web/my/myCount', heUserIdData).then((res) => {
    console.log(res);
    
    themeStore.userInfoMyCount = res.result


  });
}



</script>

<style lang="less" scoped>
.masonry-container {
  position: relative;
  width: 100%;
  height: auto;
  // padding: 0 10px;
  overflow: hidden;
}

.masonry-grid {
  position: relative;
  width: 100%;
  height: 100%;
}

.masonry-item {

  width: calc(100% / 6 - 16px);
  margin-bottom: 16px;
  box-sizing: border-box;
  transition: all 0.3s ease;

}

@media (max-width: 1200px) {
  .masonry-item {
    width: calc(100% / 5 - 16px);
  }
}

@media (max-width: 992px) {
  .masonry-item {
    width: calc(100% / 4 - 16px);
  }
}

@media (max-width: 768px) {
  .masonry-item {
    width: calc(100% / 3 - 16px);
  }
}

@media (max-width: 480px) {
  .masonry-item {
    width: calc(100% / 2 - 16px);
  }
}

.responsive-image-frame {
  position: relative;
  overflow: hidden;
  box-shadow: 0 0 3px -1px #bbb;
  border-radius: 8px;
}

.icon-edit {
  position: absolute;
  right: 1vw;
  top: 1vw;
  width: 2.5vw;
  height: 2.5vw;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 100;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 0.52vw;
  color: #fff;
  font-size: 1vw;

  img {
    width: 50%;
  }
}

.responsive-image {
  width: 100%;
  height: auto;
  border-radius: 8px;
  display: block;
  transition: transform 0.3s;
  cursor: pointer;
}

.responsive-image:hover {
  transform: scale(1.1);
}

.card-content {
  border-radius: 0 0 8px 8px;
  cursor: pointer;
}

.card-content .name {
  display: flex;
  margin-top: 10px;
  color: #333333;
  font-size: 16px;
}

.card-content .name>img {
  width: 1.5vw;
  height: 1.5vw;
  border-radius: 50%;
}

.card-content .name>p {
  margin-left: 10px;
}

.text {
  font-size: 0.83vw;
  text-align: left;
  color: var(--color-text-6);
  margin: 6px 0px;
}

p {
  font-size: 0.83vw;
  color: var(--color-text-3);
}

.icfont_box {
  width: 30%;
  height: auto;
  position: absolute;
  bottom: 12px;
  left: 14px;
  display: flex;
  align-items: center;
  gap: 10px;
  cursor: pointer;
}


.icfont_box>div {
  display: flex;
  align-items: center;
}

.icon-empty,
.icon-real {
  width: 1.56vw;
  height: 1.56vw;
  border-radius: 0.52vw;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}

.icon-empty {
  background-color: rgba(0, 0, 0, 0.5);

  .img_png {
    width: 1vw;
    height: 1vw;
  }
}

.icon-real {
  background-color: rgba(0, 0, 0, 0.5);
  opacity: 0.9;

  .img_png {
    width: 1vw;
    height: 1vw;
  }
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
  width: 100%;
}

.custom-spin :deep(.ant-spin-dot-item) {
  // background-color: var(--color-Sel);
  /* 修改旋转点颜色 */
}


// wap样式
.card-content-wap {
  width: 100%;


  .text-wap {
    font-size: 16px;
    text-align: left;
    margin: 6px 0px;
    color: var(--color-text-6);

  }

  .name-wap {
    display: flex;
    align-items: center;
    margin-top: 10px;
    color: #333333;
    cursor: pointer;


  }

  .name-wap>img {
    width: 40px;
    height: 40px;
    border-radius: 50%;
  }

  .name-wap>p {
    font-size: 14px;
    color: var(--color-text-3);
    margin-left: 10px;
    cursor: pointer;
  }



}

.icfont_box-wap {
  // width: 40%;
  height: 35px;
  position: absolute;
  bottom: 10px;
  left: 12px;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10px;

  .icon-real-wap {
    width: 35px;
    height: 35px;
    background-color: rgba(0, 0, 0, 0.5);
    border-radius: 10px;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;

    .img_png-wap {
      width: 20px;
      height: 20px;

    }
  }

  .icon-empty-wap {
    width: 35px;
    height: 35px;
    background-color: rgba(0, 0, 0, 0.5);
    border-radius: 10px;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;

    .img_png-wap {
      width: 20px;
      height: 20px;
    }

  }
}

.Pendingapproval {
  padding: 10px;
  position: absolute;
  bottom: 10px;
  right: 6px;
  color: #fff;
  border-radius: 10px;
  background-color: rgba(0, 0, 0, 0.7);
}
</style>